import axios from 'axios'
import router from '../router/index'
import toolUtil from '@/utils/toolUtil'
import config from '@/utils/config'
import { ElMessage } from 'element-plus'

const http = axios.create({
    timeout: 1000 * 86400,
    withCredentials: true,
    baseURL: (process.env.VUE_APP_BASE_API_URL || 'http://localhost:8080') + (process.env.VUE_APP_BASE_API || '/cl29556703') + '/',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    }
})

// 添加请求URL日志
http.interceptors.request.use(config => {
    console.log('请求URL:', config.baseURL + config.url)
    return config
})
// 请求拦截
http.interceptors.request.use(config => {
    // 定义不需要token的白名单接口
    const whiteList = [
        '/common/sendLoginSmsCode',
        '/common/smsLogin',
        '/login',
        '/smsLogin'
    ]
    
    // 检查当前请求是否在白名单中
    const isWhiteList = whiteList.some(path => config.url.includes(path))
    
    // 如果不是白名单接口，才添加token
    if (!isWhiteList) {
        config.headers['Token'] = toolUtil.storageGet('frontToken')
    }
    return config
}, error => {
    return Promise.reject(error)
})
// 响应拦截
http.interceptors.response.use(response => {
    if (response.data && response.data.code == 401) { // 401, token失效
        // 检查当前是否已经在登录页面
        if (router.currentRoute.value.path !== '/login' && router.currentRoute.value.path !== '/smsLogin') {
            toolUtil.storageClear()
            toolUtil.storageSet('toPath', window.history.state.current)
            ElMessage.error(response.data.msg)
            router.push('/login')
        }
        return Promise.reject(response)
    }
    else if(response.data && response.data.code == 0){
        return response
    }else{
        ElMessage.error(response.data.msg)
        return Promise.reject(response)
    }
}, error => {
    return Promise.reject(error)
})
export default http
